'use strict';

const db = uniCloud.database();
const intimateCollection = db.collection('intimate_records');

exports.main = async (event, context) => {
	// 获取用户ID和日期
	const { userId, date, hasProtection = false, mood = 3, notes = '' } = event;
	
	if (!userId || !date) {
		return {
			code: 1,
			message: '缺少必要参数'
		}
	}
	
	try {
		// 解析日期，确保正确处理本地时区
		const dateParts = date.split('-');
		if (dateParts.length !== 3) {
			return {
				code: 2,
				message: '日期格式错误，应为YYYY-MM-DD'
			}
		}
		
		// 创建指定日期的0点时刻，按照本地时区而非UTC
		const year = parseInt(dateParts[0]);
		const month = parseInt(dateParts[1]) - 1; // 月份从0开始
		const day = parseInt(dateParts[2]);
		const recordDate = new Date(Date.UTC(year, month, day, 0, 0, 0));
		
		// 检查该日期是否已经有记录
		const existRecord = await intimateCollection.where({
			user_id: userId,
			date: recordDate
		}).limit(1).get();
		
		// 如果已存在记录，返回成功（不重复添加）
		if (existRecord.data && existRecord.data.length > 0) {
			return {
				code: 0,
				message: '该日期已存在亲密记录',
				data: existRecord.data[0]
			}
		}
		
		// 添加新记录
		const result = await intimateCollection.add({
			user_id: userId,
			date: recordDate,
			has_protection: hasProtection,
			mood,
			notes
		});
		
		return {
			code: 0,
			message: '添加亲密记录成功',
			data: {
				_id: result.id,
				userId,
				date: recordDate,
				hasProtection,
				mood,
				notes
			}
		}
	} catch (error) {
		console.error('添加亲密记录失败:', error);
		return {
			code: 500,
			message: '添加亲密记录失败:' + error.message
		}
	}
}; 